#include "registerwidget.h"
#include "ui_registerwidget.h"

RegisterWidget::RegisterWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RegisterWidget)
{
    ui->setupUi(this);
    loadStyleSheet("C:/Users/shafl/Desktop/FrameWork/css/img.css");
    ui->linePasswd->clear();
    ui->lineUserName->clear();
    connect(ui->bntCancel,&QPushButton::clicked,this,[this](){
        emit selectStackWidget(0);
    });
    connect(ui->bntOK,&QPushButton::clicked,this,&RegisterWidget::onRegister);

}

RegisterWidget::~RegisterWidget()
{
    delete ui;
}

void RegisterWidget::loadStyleSheet(const QString &CssPath)
{
    QFile file(CssPath);
    if(!file.open(QIODevice::ReadWrite)){
        qDebug() << "open file failed";
        return;
    }
    this->setStyleSheet(file.readAll());
}

void RegisterWidget::onRegister()
{
    UserName = ui->lineUserName->text();
    PassWord = ui->linePasswd->text();
    if(UserName.isEmpty()||PassWord.isEmpty()){
        emit sendMessage("用户名或密码不能为空");
        return;
    }
    if (!registerSqlOperator.openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        qDebug() << "Failed to open database:" << registerSqlOperator.lastError();
        emit sendMessage("数据库连接错误");
        return;
    }
    QList<QVariantMap> users = registerSqlOperator.selectData("users","name='" + UserName + "'");
    if(!users.isEmpty()){
        emit sendMessage("已存在该用户");
        ui->lineUserName->clear();
        ui->linePasswd->clear();
        registerSqlOperator.closeDatabase();
        return;
    }
    if(registerSqlOperator.tableExists("users")){
        QVariantMap data;
        data["name"] = UserName;
        data["passwd"] = PassWord;
        if (!registerSqlOperator.insertData("users", data)) {
            qDebug() << "Failed to insert data:" << registerSqlOperator.lastError();
            emit sendMessage("注册失败");
            registerSqlOperator.closeDatabase();
            return;
        }
        registerSqlOperator.closeDatabase();
        emit sendMessage("注册成功");
    }else{
        QStringList fields;
        fields << "name TEXT NOT NULL"
               << "passwd TEXT NOT NULL";
        if (!registerSqlOperator.createTable("users", fields)) {
            qDebug() << "Failed to create table:" << registerSqlOperator.lastError();
            emit sendMessage("数据库表错误");
            registerSqlOperator.closeDatabase();
            return;
        }
        QVariantMap data;
        data["name"] = UserName;
        data["passwd"] = PassWord;
        if (!registerSqlOperator.insertData("users", data)) {
            qDebug() << "Failed to insert data:" << registerSqlOperator.lastError();
            emit sendMessage("注册失败");
            registerSqlOperator.closeDatabase();
            return;
        }
        registerSqlOperator.closeDatabase();
        emit sendMessage("注册成功");
    }
}

